package com.yutel.amote.service;

import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class AmoteConstant {
	private final static String TAG = "AppType";
	private final static Map<String, String> key = new HashMap<String, String>();
	private static AmoteConstant amoteConstant;
	private static boolean query = true;
	private static DBHelper db;

	private AmoteConstant(Context context) {
		db = new DBHelper(context);
	}

	public static AmoteConstant getInstance(Context context) {
		if (amoteConstant == null) {
			amoteConstant = new AmoteConstant(context);
		}
		return amoteConstant;
	}

	public String getKey(String keys) {
		Log.d(TAG, "query state=" + query);
		if (query) {
			querys();
			query = false;
		}
		return key.get(keys);
	}

	public void save(String key, String value) {
		query = true;
		if (exsit(key)) {
			update(key, value);
		} else {
			insert(key, value);
		}
	}

	private void querys() {
		key.clear();
		SQLiteDatabase data = db.getReadableDatabase();
		Cursor cursor = data.rawQuery("select * from amote", null);
		while (cursor.moveToNext()) {
			key.put(cursor.getString(0), cursor.getString(1));
		}
		cursor.close();
	}

	private void insert(String key, String value) {
		SQLiteDatabase data = db.getReadableDatabase();
		data.execSQL("insert into amote(akey,avalue) values(?,?)",
				new Object[] { key, value });
		Log.d(TAG, "insert table data");
	}

	private void update(String key, String value) {
		SQLiteDatabase data = db.getReadableDatabase();
		data.execSQL("update amote set avalue=? where akey=?", new Object[] {
				value, key });
		Log.d(TAG, "update table data");
	}

	private boolean exsit(String key) {
		boolean res = false;
		SQLiteDatabase data = db.getReadableDatabase();
		Cursor cursor = data.rawQuery("select * from amote where akey=?",
				new String[] { key });
		if (cursor.moveToNext()) {
			res = true;
		}
		cursor.close();
		return res;
	}
}
